﻿using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using SUNRPA.CONTROLS.IMPL.util;
using System.Collections.Concurrent;

namespace SUNRPA.CONTROLS.IMPL.controls {
    public class CopyFileNAction: BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            CopyFileNParam? param = item.ControlParam as CopyFileNParam;
            string waitCopyFile = param.WaitCopyFile;
            string targetParentPath = param.TargetParentPath;
            string afterCopyPath = param.AfterCopyPath;
            int ifExist = param.IfExist;
            this.GetStringVar(ref waitCopyFile, globleData);
            this.GetStringVar(ref targetParentPath, globleData);
            if(!File.Exists(waitCopyFile)){ 
                throw new RpaRuntimeException("需要复制的文件不存在");
            }
            FileInfo fileInfo = new FileInfo(waitCopyFile);
            string fileName = fileInfo.Name;
            string copyFullName = targetParentPath + Path.DirectorySeparatorChar + fileName;
            switch(ifExist) {
                case 0:
                    //覆盖
                    fileInfo.CopyTo(copyFullName, true);
                    break;
                case 1:
                    //不拷贝
                    fileInfo.CopyTo(copyFullName, false);
                    break;
                case 2:
                    //自动添加后缀
                    int count = 1;
                    int nameEndIndex = fileName.LastIndexOf(".");
                    if(nameEndIndex < 0) { 
                        nameEndIndex = fileName.Length;
                    }
                    string nameOnly = fileName.Substring(0, nameEndIndex);
                    while(File.Exists(copyFullName)) { 
                        copyFullName = $"{targetParentPath}{Path.DirectorySeparatorChar}{nameOnly}({count}){fileInfo.Extension}";
                        count++;
                    }
                    fileInfo.CopyTo(copyFullName, false);
                    break;
                default:
                    break;
            }
            this.saveVar(globleData, afterCopyPath, new StringModel(afterCopyPath, copyFullName), DefaultContents.RUNNING_PARAM);
            return currentIndex;
        }
    }
}
